<template>
  <view style="overflow: hidden">
    <up-navbar v-if="VisibleandHidden" :title="title" :autoBack="false" placeholder @leftClick="closePopup"></up-navbar>
    <view class="box-headinput">
      <view class="search-bar">
        <u-icon name="search" size="18" color="#999" class="search-icon" />
        <input v-model="keywordvalue" class="search-input" type="text" placeholder="请输入名称"
          placeholder-class="search-placeholder" />
      </view>
    </view>

    <view class="box-head">
      <PickerHeader ref="refUniMallHead" @change="tabChange"></PickerHeader>
    </view>


    <scroll-view scroll-y="true" :style="listHeightStyle">
      <view class="box-list">
        <template v-for="item in currentData" :key="item.id">
          <view class="box-list-item" :class="[
            item.children && item.children.length ? 'box-list-item-dept-icon' : '',
            item.type === 'user' ? 'box-list-item-user' : 'box-list-item-dept'
          ]" @click="handelClickItem(item)">
            <radio @click="handelClickItem(item)" v-if="item.type === 'user'" v-show="_entry == 'component'"
              style="transform: scale(0.8)" :checked="setChecked(item)" />
            <radio @click="handelClickItem(item)" v-if="item.type === 'dept' && _type == 'dept'"
              v-show="_entry == 'component'" style="transform: scale(0.8)" :checked="setChecked(item)" />
            <view class="box-list-item-dept-pic" v-if="item.type === 'dept'">
              <image src="@/static/dept-icon.png"></image>
            </view>
            <view class="box-list-item-user-pic" v-else>
              <!-- <image v-if="item.avatar" :src="item.avatar" mode="aspectFill"></image> -->
              <!-- image-local url-->
              <image-local v-if="item.avatar" :id="item.id" :url="item.avatar" radius="10rpx" width="40px"
                height="50px"></image-local>
              <text v-else>{{ getUserName(item.name) }}</text>
            </view>
            <view class="box-list-item-right">
              <view class="box-list-item-text">{{ item.name }} {{ item.children && item.children.length > 0 ?
                `（${item.children.length}）` : '' }}</view>
              <!-- 角色标签 职务 -->
              <view class="box-list-item-user-tag" v-if="item.type === 'user' && item.tag && item.type.length > 0">
                <text v-for="(tag, tagIndex) in item.tag">{{ tag }}</text>
              </view>
              <!-- 部门切换下级 -->
              <view class="box-list-item-user-tag tag-c" v-if="item.type === 'dept'"
                @click="handelClickItem(item, true)">
                <text style="font-size: 30rpx;">下级</text>
              </view>
            </view>
          </view>
        </template>
      </view>
    </scroll-view>

    <view class="select-container" v-show="_entry == 'component'">
      <view class="select-left">
        <text>已选择（{{ selection.length }}）:</text>
      </view>

      <!-- 单选 -->
      <view v-if="!_multiple" class="scrollContainer">
        <view v-for="item in selection" :key="item.id" class="single-item">
          <text>{{ item.name }}</text>
        </view>
      </view>
      <!-- 多选左右滚动 -->
      <scroll-view v-else class="scrollContainer" scroll-x>
        <view style="display: flex;" @click="show = true">
          <view v-for="item in selection" :key="item.id" class="select-item">
            <!-- 替换本地 -->
            <!-- <image v-if="item.avatar" mode="aspectFill" :src="item.avatar"></image> -->
            <!--             #ifdef APP-PLUS-->
            <image-local v-if="item.avatar" :id="item.id" :url="item.avatar" radius="6rpx" width="72rpx"
              height="72rpx"></image-local>
            <text v-else>{{ item.name }}</text>
            <!--             #endif-->

            <!--             #ifdef H5-->
            <view class="h5-image-wrapper" v-if="item.avatar">
              <image :src="item.avatar" :style="{ width: '72rpx', height: '72rpx', borderRadius: '6rpx' }"
                @error="handleH5ImageError(item)" mode="aspectFill" />
              <text v-if="item.showTextInstead" class="fallback-text">{{ getFallbackName(item.name) }}</text>
            </view>
            <text v-else>{{ item.name }}</text>
            <!--             #endif-->
          </view>
        </view>
      </scroll-view>
      <view class="select-right">
        <up-button @click="submit" :customStyle="{ border: 'none', width: '92rpx', height: '52rpx' }"
          :disabled="selection.length == 0" type="primary" text="确定"></up-button>
      </view>
    </view>
    <!-- 弹出框 -->
    <up-popup :show="show" @close="show = fasle" :customStyle="{ height: '56vh' }">
      <view class="popup-header">
        <view @click="show = false">
          <up-icon :size="18" bold name="close"></up-icon>
        </view>
        <view style="font-weight: 500;">已选择({{ selection.length }})</view>
        <view @click="show = false">确定</view>
      </view>
      <view class="popup-content">
        <view v-for="item in selection" :key="item.id" class="select-item">
          <view style="display: flex; align-items: center;">
            <!-- 替换本地 -->
            <!-- <image v-if="item.avatar" :src="item.avatar" mode="aspectFill"></image> -->
            <image-local v-if="item.avatar" :id="item.id" :url="item.avatar" radius="6rpx" width="72rpx"
              height="72rpx"></image-local>
            <text v-else>{{ item.name }}</text>
            <view>{{ item.name }}</view>
          </view>
          <view>
            <up-button :customStyle="{ border: 'none' }" plain size="mini" :hairline="false" @click="removeAndAdd(item)"
              text="移除"></up-button>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script>
import base from '@/apis/cloud/base';
import ImageLocal from '@/components/image-local/image-local.vue';
import { SysAvatar } from '@/utils/sql/avatar';
import PickerHeader from './picker-header.vue';
export default {
  components: {
    PickerHeader,
    ImageLocal
  },
  props: {
    // page页面使用 component组件使用
    entry: {
      type: String,
      default: 'page'
    },
    type: {
      type: String,
      default: 'user'
    },
    multiple: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      show: false,
      currentData: [],
      defaultHeadList: { name: '江苏绿港', id: '1' },
      dataList: [{
        id: 1,
        name: "江苏绿港",
        type: "dept",
        person_num: 400
      }],
      selection: [],
      topHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      keywordvalue: '',
      itemid: null,
      objid: null,
      title: '',
      VisibleandHidden: false,
      source: '',
      _multiple: true,
      _entry: 'page',
      _type: 'user',
      option: {},
      fuzhiItemid: '',
      pathStack: [], // 存放层级路径
    };
  },
  watch: {
    keywordvalue (val) {
      this.getCurrentData();
    },
  },
  onLoad (option) {
    this.option = option
    console.log('option', option)
    this.title = option.title || this.title
    this.VisibleandHidden = option.VisibleandHidden || this.VisibleandHidden
    this.source = option.source || this.source
    this._multiple = option.multiple == 'false' ? false : true || this.multiple
    this._entry = option._entry || this.entry
    this._type = option._type || this.type
    this.fuzhiItemid = option.fuzhiItemid || ''
  },
  created () {
    this._multiple = this.option.multiple == 'false' ? false : true || this.multiple
    this._entry = this.option._entry || this.entry
    this._type = this.option._type || this.type
    this.calculateListHeight();
  },
  mounted () {
    this.init();

  },
  methods: {
    closePopup () {
      uni.navigateBack({ delta: 1 });
    },
    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight; // 顶部安全高度
      const headerHeight = 97; // 顶部操作区域、搜索框等的高度

      // #ifdef APP-PLUS
      this.listHeightStyle = {
        height: `90vh`,
        overflowY: 'auto',
        paddingBottom: '40rpx',

      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - headerHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'auto',
      };
      // #endif
    },
    handleH5ImageError (item) {
      this.$set(item, 'showTextInstead', true); // 添加响应式字段
    },
    getFallbackName (name) {
      if (!name) return '';
      if (name.length <= 2) return name;
      return name.slice(-2); // 取最后两个字
    },
    submit () {
      this.$emit('ok', this.selection);
      // ProcessRender 流程图
      if (this.VisibleandHidden) {

        this.jumpto()


      }
    },
    isEntry () {
      if (this._entry == 'page') return false;
    },
    async init (id) {
      if (Object.keys(this.defaultHeadList).length > 0) {
        this.$refs.refUniMallHead.addTab(this.defaultHeadList);
      }

      // 创建 sys_avatar
      //#ifdef APP-PLUS
      await SysAvatar.init();
      // #endif

      this.getCurrentData(1);
    },
    // 是否选中
    setChecked (event) {
      const findIndex = this.selection.findIndex(item => item.id == event.id)
      if (findIndex != -1) {
        return true
      } else {
        return false
      }
    },
    // 顶部部门切换
    tabChange (obj) {
      this.defaultHeadList = obj;
      this.getCurrentData(obj.id, true);

      // 回退 pathStack
      const index = this.pathStack.findIndex(d => d.id === obj.id)
      if (index !== -1) {
        this.pathStack = this.pathStack.slice(0, index + 1)
      }
    },

    handelClickItem (item, change) {
      // // 切换部门 获取数据
      // if ((item.type === 'dept' && this._type != 'dept') || change) {
      //   this.getCurrentData(item.id);
      //   this.defaultHeadList = item;
      //   this.$refs.refUniMallHead.addTab({ name: item.name, id: item.id });
      //   this.pathStack.push({ name: item.name, id: item.id })
      //   return
      // }
      // this.$emit('change', item);
      // this.removeAndAdd(item);
      // 切换部门 获取数据
      if ((item.type === 'dept' && this._type != 'dept') || change) {
        // 如果当前 tab 已经是这个部门，就不重复添加
        const lastTab = this.pathStack[this.pathStack.length - 1]
        if (!lastTab || lastTab.id !== item.id) {
          this.$refs.refUniMallHead.addTab({ name: item.name, id: item.id });
          this.pathStack.push({ name: item.name, id: item.id })
        }

        this.getCurrentData(item.id);
        this.defaultHeadList = item;
        return
      }
      this.$emit('change', item);
      this.removeAndAdd(item);
    },
    removeAndAdd (item) {
      // 选中
      const findIndex = this.selection.findIndex(i => item.id == i.id);
      if (findIndex != -1) {
        this.selection.splice(findIndex, 1);
      } else {
        if (this._multiple) {
          this.selection.push(item);
          const arr = [...new Set(this.selection)];
          this.selection = arr;
        } else {
          this.selection = [item];
        }
      }
    },
    // 名称处理
    getUserName (name) {
      if (name.length === 0) {
        return '';
      } else if (name.length <= 2) {
        return name;
      } else if (name.length >= 3) {
        return name.substring(name.length - 2);
      }
    },
    async changeUpinput () {
      console.log('this.keywordvalue', this.keywordvalue)
    },
    // 获取数据
    async getCurrentData (id, topTabChange) {
      if (id !== this.defaultHeadList.id || topTabChange) {
        const msg = await base.getGroupData({ deptId: id, type: this._type, keyword: this.keywordvalue });
        this.currentData = msg.data;
      }
    },

    jumpto () {
      const newSelection = this.selection.map(item => {
        if (item.type === 'dept') {
          const pathNames = this.pathStack.map(d => d.name).concat(item.name)
          return {
            ...item,
            name: pathNames.join('-')
          }
        }
        return item
      })
      if (this.source == 'ProcessRender') {
        uni.$emit('applyProcessRender', this.selection)
      } else if (this.source == 'UserPicker') {
        uni.$emit('applyUserPicker', {
          'fuzhiItemid': this.fuzhiItemid,
          data: this.selection
        })
      } else if (this.source == 'DeptPicker') {
        uni.$emit('applyDeptPicker', {
          'fuzhiItemid': this.fuzhiItemid,
          data: newSelection || this.selection
        })
      } else if (this.source == 'applyOrderDetail') {
        uni.$emit('applyOrderDetail', this.selection)
      } else if (this.source == 'RelatedpopupsDetail') {
        uni.$emit('RelatedpopupsDetail', this.selection)
      } else if (this.source == 'WorklogAddUser') {
        uni.$emit('WorklogAddUser', this.selection)
      } else if (this.source == 'passon') {
        uni.$emit('passon', this.selection)
      }
      uni.navigateBack({ delta: 1 });
    },
  }
};
</script>

<style lang="scss" scoped>
.h5-image-wrapper {
  position: relative;
  display: inline-block;
}


.search-bar {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 10px;
  padding: 0 20rpx;
  height: 60rpx;
  box-sizing: border-box;
}

.search-icon {
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  border: none;
  background-color: transparent;
  font-size: 28rpx;
  color: #333;
}

.search-placeholder {
  color: #999;
}


.fallback-text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  color: white;
  background-color: rgba(0, 0, 0, 0.3); // 可选背景色增强可读性
  text-align: center;
}

.box-headinput {
  position: fixed;
  left: 0px;
  width: 100%;
  height: 48px;
  padding-left: 20rpx;
  padding-right: 20rpx;
  background: #ffffff;
  box-sizing: border-box;
  overflow-y: hidden;
  z-index: 9999;
}


.box-head {
  position: fixed;
  left: 0px;
  width: 100%;
  height: 48px;
  //#ifdef APP-PLUS
  top: 210rpx;
  // #endif

  // #ifdef H5
  top: 150rpx;
  // #endif
  background: #ffffff;
  padding-left: 17px;
  box-sizing: border-box;
  overflow-y: hidden;
  z-index: 9999;
}

.box-list {
  //#ifdef APP-PLUS
  padding-top: 70px;
  // #endif

  // #ifdef H5
  padding-top: 82px;

  // #endif
  .box-list-item {
    position: relative;
    height: 60px;
    display: flex;
    align-items: center;
    padding: 0 14px;
    box-sizing: border-box;
    background: #ffffff;
    margin-bottom: 1px;

    &:active {
      background: #f2f3f4;
    }

    &:last-child {
      margin-bottom: 0px;
    }

    .box-list-item-dept-pic {
      width: 40px;
      height: 40px;
      background: rgba(55, 127, 255, 0.1);
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 14px;
      overflow: hidden;

      image {
        width: 20px;
        height: 20px;
      }
    }

    .box-list-item-user-pic {
      width: 40px;
      height: 40px;
      background: #377fff;
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 14px;
      overflow: hidden;

      image {
        width: 40px;
        height: 40px;
      }

      text {
        color: #ffffff;
        font-size: 12px;
      }
    }

    .box-list-item-right {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex: 1;
    }

    .box-list-item-text {
      color: #333333;
      font-size: 16px;
    }

    .box-list-item-user-tag {
      text {
        box-sizing: border-box;
        border-radius: 8px;
        padding: 4px 8px;
        font-size: 10px;
        margin-left: 5px;

        &:first-child {
          margin-left: 0px;
        }

        &:nth-child(1) {
          background: rgba(49, 210, 144, 0.05);
          color: #31d290;
        }

        &:nth-child(2) {
          background: rgba(55, 127, 255, 0.05);
          color: #377fff;
        }
      }
    }

    .tag-c {
      text {
        color: #377fff !important;
      }
    }

    &.box-list-item-dept-icon {
      &::after {
        content: '';
        position: absolute;
        width: 5px;
        height: 10px;
        top: 26px;
        right: 15px;
        background: url(@/static/more.png) no-repeat;
      }
    }
  }
}

.select-container {
  position: fixed;
  box-sizing: border-box;
  bottom: 0;
  padding: 30rpx 20rpx;
  width: 100vw;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #E1E3E5;

  .scrollContainer {
    width: 60%;
    display: flex;
  }

  .select-left {
    font-size: 26rpx;
    width: 25%;
  }

  .select-right {
    width: 10%;
  }
}

.single-item {
  text {
    font-size: 32rpx;
  }
}

.select-item {
  display: flex;
  align-items: center;
  justify-content: space-between;

  image {
    display: inline-block;
    width: 60rpx;
    height: 60rpx;
    border-radius: 6rpx;
    margin: 0 4rpx;
  }

  text {
    display: inline-block;
    width: 60rpx;
    height: 60rpx;
    text-align: center;
    font-size: 20rpx;
    line-height: 60rpx;
    border-radius: 6rpx;
    background-color: #2979ff;
    color: #fff;
    margin: 0 4rpx;
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  padding: 30rpx;
}

.popup-content {
  .select-item {
    margin-bottom: 10rpx;
    border-bottom: 1px solid #E1E3E5;
    padding: 14rpx 20rpx;

    image {
      width: 72rpx;
      height: 72rpx;
    }

    text {
      width: 72rpx;
      height: 72rpx;
      font-size: 24rpx;
      line-height: 72rpx;
    }

    view {
      font-size: 28rpx;
      margin-left: 24rpx;
    }
  }

  .select-item:last-child {
    border: none !important;
  }
}
</style>
